<script  setup>
import {reactive } from 'vue'

let ids = []
const camerIds = navigator.mediaDevices.enumerateDevices()
console.log(camerIds)
camerIds.then(d=>{
    d.forEach(item=>{
        if(item.kind==='videoinput'){
            ids.push(item)
        }
    })
}
)

let step = 0
const switchCameraFn = ()=> {
    let totalNum = ids.length - 1
    if(step >= totalNum) step = 0
    else if(step < totalNum) step++

    const valObj = navigator.mediaDevices.getUserMedia({
        audio: false,
        video: {
            deviceId: {exact: ids[step].deviceId}
        }
    })
    playLoclaStrem(valObj)
}

function playLoclaStrem(streamObj) {
    streamObj.then(d=>{
        const videoEl = document.getElementById('localVideo')
        videoEl.srcObject = d
    })
}



let picUrl = reactive({
    arr: []
})
const takePhotoFn = ()=> {
    const videoEl = document.getElementById('localVideo')
    const canvas = document.createElement('canvas')
    canvas.width=200
    canvas.height=120

    const ctx = canvas.getContext('2d')

    ctx.drawImage(videoEl, 0, 0, 200, 120)
    console.log(canvas.toDataURL('image/png'))
    picUrl.arr.push(canvas.toDataURL('image/png'))
    
}



const constraints = {
  video: true, // 尝试不指定具体约束，让浏览器决定
  // 或者提供更宽泛的约束条件
  // video: { facingMode: "user", width: { ideal: 640 }, height: { ideal: 480 } },
  audio: false
}

navigator.mediaDevices.getUserMedia(constraints)
  .then(stream => {
    // 成功处理逻辑
  })
  .catch(error => {
    if (error instanceof OverconstrainedError) {
      console.error("设备约束条件无法满足:", error);
      // 给用户提供反馈，说明请求的配置不可用
    } else {
      console.error("获取媒体流时发生错误:", error);
      // 处理其他类型的错误
    }
  });

</script>

<template>
  <h1>摄像头获取媒体流并拍照</h1>
  <video id="localVideo" autoplay playsinline muted></video>

  <van-button style="margin-right: 20px" type="primary" @click="takePhotoFn"
    >拍照</van-button
  >
  <van-button type="primary" @click="switchCameraFn">切换摄像头</van-button>

  <div>
    <img v-for="(n,m) in picUrl.arr" :key="m" :src="n" alt="" />
  </div>
</template>

<style  scoped>
div {
    margin:10px 0;
}

#localvideo {
    height: 200px;
  width: 300px;
}

img {
    width: 200px;
    height: 120px;
}
</style>
